package com.smartao.base.role;

import java.util.Set;
import java.util.TreeSet;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
import org.hibernate.annotations.ForeignKey;

import com.smartao.base.employee.Employee;
import com.smartao.base.selectitem.Selectitem;
import com.smartao.core.orm.entity.BaseEntity;
import com.smartao.core.security.SmartaoRole;

/**
 * 角色实体类
 * @author Ricky
 */
@Entity
@Table(name="T_BASE_ROLE")
public class Role extends BaseEntity<Role> implements SmartaoRole{
	
	private static final long serialVersionUID = -7963388164615663730L;
	
	@Column(nullable=false, unique=true,length=128)
	private String roleKey;
	
	@ManyToOne
	@ForeignKey(name = "none")
	@JoinColumn(name = "roleType")
	@Fetch(FetchMode.JOIN)
	private Selectitem roleType;
	
	private String name;
	private String description;

	// TODO: 此处我完善了多对多双向关联，则从role对users进行操作会很方便；
	// cascadeType不能设置为REMOVE; 它会导致role被删除的时候， user也会被删除；
	@ManyToMany(targetEntity = Employee.class, fetch = FetchType.LAZY)
	@JoinTable(name = "T_BASE_EMPLOYEE_ROLE", joinColumns = { @JoinColumn(name = "ROLE_ID", nullable = false) }, inverseJoinColumns = { @JoinColumn(name = "EMPLOYEE_ID", nullable = false) })
	@ForeignKey(name = "none", inverseName = "none")
	private Set<Employee> users;

	public Role() {}
	
	public Role(String roleKey) {
		this.roleKey = roleKey;
	}
	
	public String getRoleKey() {
		return roleKey;
	}

	public void setRoleKey(String roleKey) {
		this.roleKey = roleKey;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	public Set<Employee> getUsers() {
		return users;
	}

	public void setUsers(Set<Employee> users) {
		this.users = users;
	}

	@Override
	public String getAuthority() {
		return roleKey;
	}

	public Selectitem getRoleType() {
		return roleType;
	}

	public void setRoleType(Selectitem roleType) {
		this.roleType = roleType;
	}
	
	public void addUser(Employee employee){
		if(this.users==null){
			this.users = new TreeSet<Employee>();
		}
		if(!this.users.contains(employee)){
			this.users.add(employee);
		}
	}
	
}
